package org.wheel.plugins.toolkit.jdbc.pool.util;

import cn.hutool.core.util.StrUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DatabaseDriverUtil {

    // 缓存 JDBC URL 前缀与数据库驱动的映射关系
    private static final Map<String, String> JDBC_URL_PREFIX_MAP = new ConcurrentHashMap<>();

    static {
        // 初始化映射关系
        JDBC_URL_PREFIX_MAP.put("jdbc:mysql:", "com.mysql.cj.jdbc.Driver");
        JDBC_URL_PREFIX_MAP.put("jdbc:oracle:", "oracle.jdbc.driver.OracleDriver");
        JDBC_URL_PREFIX_MAP.put("jdbc:postgresql:", "org.postgresql.Driver");
        JDBC_URL_PREFIX_MAP.put("jdbc:sqlserver:", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
        JDBC_URL_PREFIX_MAP.put("jdbc:db2:", "com.ibm.db2.jcc.DB2Driver");
        JDBC_URL_PREFIX_MAP.put("jdbc:h2:", "org.h2.Driver");
        JDBC_URL_PREFIX_MAP.put("jdbc:hsqldb:", "org.hsqldb.jdbc.JDBCDriver");
        JDBC_URL_PREFIX_MAP.put("jdbc:sqlite:", "org.sqlite.JDBC");
        JDBC_URL_PREFIX_MAP.put("jdbc:dm:", "dm.jdbc.driver.DmDriver");
        JDBC_URL_PREFIX_MAP.put("jdbc:kingbase:", "com.kingbase8.Driver");
        JDBC_URL_PREFIX_MAP.put("jdbc:oscar:", "com.oscar.jdbc.Driver");
        JDBC_URL_PREFIX_MAP.put("jdbc:gaussdb:", "com.huawei.gauss.jdbc.Driver");
        JDBC_URL_PREFIX_MAP.put("jdbc:oceanbase:", "com.oceanbase.jdbc.Driver");
        JDBC_URL_PREFIX_MAP.put("jdbc:clickhouse:", "ru.yandex.clickhouse.ClickHouseDriver");
        JDBC_URL_PREFIX_MAP.put("jdbc:mariadb:", "org.mariadb.jdbc.Driver");
        JDBC_URL_PREFIX_MAP.put("jdbc:tidb:", "com.pingcap.tidb.jdbc.Driver");
        JDBC_URL_PREFIX_MAP.put("jdbc:kingbasees:", "com.kingbase8.Driver");
    }

    /**
     * 根据 JDBC URL 获取数据库驱动类名
     *
     * @param jdbcUrl JDBC URL
     * @return 数据库驱动类名
     */
    public static String getDriverByJdbcUrl(String jdbcUrl) {
        if (StrUtil.isBlank(jdbcUrl)) {
            throw new IllegalArgumentException("JDBC URL cannot be blank");
        }

        // 统一转为小写方便匹配
        String lowerCaseUrl = jdbcUrl.toLowerCase();

        // 遍历映射关系，找到匹配的驱动
        for (Map.Entry<String, String> entry : JDBC_URL_PREFIX_MAP.entrySet()) {
            if (lowerCaseUrl.startsWith(entry.getKey())) {
                return entry.getValue();
            }
        }

        throw new IllegalArgumentException("Unsupported JDBC URL: " + jdbcUrl);
    }
}